<?php
//PingBuWang.Com
//Copyright (c) 2017~2099 http://www.pingbuwang.com All rights reserved.
namespace app\setting\model;

use think\Cache;
use mip\Paginationm;
use think\Db;
use think\Model;
use think\Controller;

class Mainmenu extends Model
{

    public function getById($id){
        $arr = db('mainMenu')->cache('c_mainMenu_getById_'.$id)->where(array('id'=>$id))->find();
        return $arr;
    }

    public function getList($all=false){
        $arr = Cache::get('c_mainMenu_getList_'.$all);
        if($arr){
            return  $arr;
        }

        $dbitems1 = db('mainMenu');
        if(!$all){
            $dbitems1= $dbitems1->where('item_status',1);
        }
        $items1= $dbitems1->where('pid',0)->order('sort asc')->select();

        // 增加首页菜单项目
        $arr=[];

        foreach($items1 as $key =>$val){

            $pid = $val['id'];
            $dbitems2 = db('mainMenu');
            if(!$all) {
                $dbitems2 = $dbitems2->where('item_status', 1);
            }
            $items2=$dbitems2->where('pid',$pid)->order('sort asc')->select();
            $val['children'] = $items2;
            $arr[] = $val;
        }
        Cache::tag('main_menu')->set('c_mainMenu_getList_'.$all,$arr,3600);

        return $arr;
    }

    public function doAdd($arr){
        $res = db('mainMenu')->insert($arr);
        Cache::clear('main_menu');
        return $res;
    }

    public function doEdit($arr){
        $res = db('mainMenu')->where(array('id'=> $arr['id'] ))->update($arr);
        Cache::clear('main_menu');
        return $res;
    }

    public function doDelById($id ){

        $res = db('mainMenu')->where( function($q)use($id){$q->where(array('id'=>$id ))->whereOr('pid',$id);} )->delete();
        Cache::clear('main_menu');
        return $res;
    }


}